package com.fourool.goodsmall.service.impl;

import com.fourool.goodsmall.common.Result;
import com.fourool.goodsmall.dto.AddressDTO;
import com.fourool.goodsmall.entity.GAddress;
import com.fourool.goodsmall.mapper.GAddressMapper;
import com.fourool.goodsmall.service.GAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class GAddressServiceImpl implements GAddressService {

    @Autowired
    private GAddressMapper addressMapper;

    @Override
    public Result getAddressDetail(Integer id) {
        return Result.success(addressMapper.findById(id));
    }

    @Override
    public Result getAddressList(Integer pid) {
        return Result.success(addressMapper.findByPid(pid));
    }

    @Override
    @Transactional // 涉及多步数据库操作，开启事务
    public Result addAddress(Integer pid, AddressDTO dto) {
        // 如果要将新地址设为默认，则先将该用户其他地址取消默认
        if (dto.getIsdefault() == 1) {
            addressMapper.setAllNotDefault(pid);
        }

        GAddress address = new GAddress();
        address.setPid(pid);
        address.setName(dto.getName());
        address.setPhone(dto.getPhone());
        address.setAddr(dto.getAddr());
        address.setIsdefault(dto.getIsdefault());

        addressMapper.insert(address);
        return Result.success();
    }

    @Override
    @Transactional
    public Result updateAddress(Integer id, AddressDTO dto) {
        GAddress address = addressMapper.findById(id);
        if (address == null || address.getStatus() == 0) {
            return Result.error(404, "地址不存在");
        }

        // 如果要将此地址设为默认，则先将该用户其他地址取消默认
        if (dto.getIsdefault() != null && dto.getIsdefault() == 1) {
            addressMapper.setAllNotDefault(address.getPid());
        }

        // 更新字段
        address.setName(dto.getName());
        address.setPhone(dto.getPhone());
        address.setAddr(dto.getAddr());
        if (dto.getIsdefault() != null) {
            address.setIsdefault(dto.getIsdefault());
        }

        addressMapper.update(address);
        return Result.success();
    }

    @Override
    public Result deleteAddress(Integer id) {
        GAddress address = addressMapper.findById(id);
        if (address == null || address.getStatus() == 0) {
            return Result.error(404, "地址不存在");
        }

        // 软删除：将status置为0
        address.setStatus(0);
        addressMapper.update(address);
        return Result.success();
    }
}